package com.jianganming.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

//服务端处理器
public class NettyCilentHandler extends ChannelInboundHandlerAdapter {

    //读取服务端端数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        String messge = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println(ctx.channel().remoteAddress()+"说：");
        System.out.println(messge);
    }

    //向服务端写数据
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id","1");
        jsonObject.put("name","江安明");
        jsonObject.put("msg","hello,服务端，我连上你了");
        ctx.writeAndFlush(Unpooled.copiedBuffer(jsonObject.toJSONString(),CharsetUtil.UTF_8));
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
